#!/bin/bash
echo "欢迎使用云手机自动搭建脚本!"
read -p "是否已安装完依赖项并重启了termux?(请输入y或n): " choice

if [ "$choice" = "y" ]; then
    echo "开始进行配置…"
    mkdir -p /sdcard/noVNC/
    #清空文件夹
    if [ -d "/sdcard/noVNC/noVNC/" ]; then
        rm -rf /sdcard/noVNC/noVNC/
    fi
    if [ -d "/sdcard/noVNC/websockify-js/" ]; then
        rm -rf /sdcard/noVNC/websockify-js/
    fi
    if [ -f "/sdcard/noVNC/noVNC.zip" ];then
        rm /sdcard/noVNC/noVNC.zip
    fi
    cd /sdcard/noVNC/
    wget -O noVNC.zip https://gitee.com/caofangkuai/CloudMobilePhoneAutomaticConfigurationScript/raw/master/noVNC.zip
    unzip noVNC.zip
    cd /sdcard/noVNC/websockify-js/websockify/
    read -p "请输入droidVNC-NG软件提供的IP:PORT地址(点击START按钮，完成相应授权，STOP按钮下面的一行小字“The server is now reachable at xxx.xxx.x.xxx:5900”后面的IP地址和端口): " link
    read -p "请输入你想要的noVNC端口(建议6080): " noVNCPort
    read -p "是否进行内网穿透?(请输入y或n): " yn
    if [ "$yn" = "y" ]; then
        sv up cpolar
        #echo "请前往 http://localhost:9200/ 配置内网穿透，参考 https://www.cpolar.com/blog/cpolar-quick-start-tutorial-termux-series/"
        read -p "请输入登录cpolar后台仪表盘：https://dashboard.cpolar.com/，验证菜单里的token值: " token
        cpolar authtoken $token
        arr=$link | awk '{split($0,arr,":");for(i in arr) print i,arr[i]}'
        cpolar tcp $(expr $arr + 0)
        cpolar http $(expr $noVNCPort + 0)
    fi
    read -p "请输入上面第一个弹窗的Forwarding项内容(去掉tcp://): " vncgw
    if [ "$yn" = "y" ]; then
      echo "配置完成，可通过上面第二个弹窗的的Forwarding项内容(公网IP)进行访问，公网IP可能会不定期更变"
    else
      echo "配置完成，可通过内网 localhost:$noVNCPort/vnc.html 进行访问"
    fi
    cd /sdcard/noVNC/websockify-js/websockify/
    node websockify.js --web /sdcard/noVNC/noVNC/ $(expr $noVNCPort + 0) $vncgw 1
else
    echo "开始安装依赖项…"
    apt install zip -y
    pkg install nodejs -y
    pkg install wget -y
    mkdir -p $PREFIX/etc/apt/sources.list.d
    echo "deb [trusted=yes] http://termux.cpolar.com termux extras" >> $PREFIX/etc/apt/sources.list.d/cpolar.list
    pkg update -y
    pkg install cpolar -y
    pkg install termux-services -y
    echo "依赖项安装完成，请重启termux"
fi